from typing import List

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from database.manager import DbManager
from database.models import User as UserModel
from database.schemas.user import UserResponse, UserCreate
from security import check_token

router = APIRouter()

db_manager = DbManager()


@router.get("/", response_model=List[UserResponse])
def get_users(db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    users = db.query(UserModel).all()
    return users


@router.get("/{user_id}", response_model=UserResponse)
def get_user(user_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user


@router.post("/", response_model=UserResponse)
def add_user(user: UserCreate, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    existing_user = db.query(UserModel).filter(UserModel.id == user.id).first()
    if existing_user is not None:
        raise HTTPException(status_code=400, detail="User with this ID already exists")
    db_user = UserModel(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


@router.delete("/{user_id}", response_model=UserResponse)
def delete_user(user_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    db.delete(user)
    db.commit()
    return {"detail": "User deleted"}


@router.put("/{user_id}", response_model=UserResponse)
def edit_user(user_id: int, user: UserCreate, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    db_user.first_name = user.first_name
    db_user.last_name = user.last_name
    db_user.username = user.username
    db_user.is_admin = user.is_admin
    db.commit()
    db.refresh(db_user)
    return db_user